﻿using System.ComponentModel;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: TagPrefix("Softio.Mscd.Client", "mvc")]

namespace Softio.Mscd.Client
{
    /// <summary>
    /// Minify content removing whitespace and other unnecessary signs.
    /// </summary>
    [ToolboxItem(false)]
    [ToolboxData(@"<{0}:MinifiedContentPlaceHolder runat=""server""></{0}:MinifiedContentPlaceHolder>")]
    public class MinifiedContentPlaceHolder : ContentPlaceHolder
    {
        public MinifiedContentPlaceHolder()
        {
            ContentType = StaticFile.ContentTypes.JavaScript;
        }

        /// <summary>
        /// Content type. Default is JavaScript.
        /// </summary>
        public StaticFile.ContentTypes ContentType { get; set; }

        /// <summary>
        /// Set to <c>true</c> to test minifying. Otherwise minify works only when debugging is disabled.
        /// </summary>
        public bool TestMinify { get; set; }

        /// <summary>
        /// Sends server control content to a provided System.Web.UI.HtmlTextWriter object, 
        /// which writes the content to be rendered on the client.
        /// </summary>
        /// <param name="writer">The System.Web.UI.HtmlTextWriter object that receives the server control content.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            if (Context.IsDebuggingEnabled && !TestMinify)
            {
                base.Render(writer);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                using (HtmlTextWriter sw = new HtmlTextWriter(new StringWriter(sb)))
                {
                    base.Render(sw);
                }
                writer.Write(MinifiedControlsHelper.Minify(ContentType, sb.ToString()));
            }
        }
    }
}
